package com.augmentum.login.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.augmentum.login.Constants;
import com.augmentum.login.model.User;
import com.augmentum.login.util.PathUtil;
import com.augmentum.login.util.StringUtil;

public class SessionFilter implements Filter {

    private String exceptUrl = "";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
            ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        String url = httpRequest.getRequestURI();
        String requestUrl = url.substring(httpRequest.getContextPath().length()+1);
        String[] pages = exceptUrl.split(",");
        boolean isAlive = false;
        for (String page : pages) {
            if (requestUrl.equals(page)) {
                isAlive = true;
                break;
            }
        }

        if (isAlive) {
            filterChain.doFilter(request, response);
        } else {
            HttpSession session = httpRequest.getSession();
            User user = (User)session.getAttribute(Constants.USER);
            if (user == null) {
                String method = httpRequest.getMethod().toLowerCase();
                String queryStr = httpRequest.getQueryString();
                if (StringUtil.isEmpty(queryStr)) {
                    queryStr = "";
                }
                if (method.equals("get")) {
                    httpResponse.sendRedirect(PathUtil.getFullPath("user/loginPage") + "?go=" + requestUrl + "#" + queryStr);
                } else if (method.equals("post")){
                    httpResponse.sendRedirect(PathUtil.getFullPath("user/loginPage") + "?go=page/" + Constants.SEARCH_QUESTION_SERVLET);
                } else {
                    httpResponse.sendRedirect(httpRequest.getContextPath());
                }
            } else {
                filterChain.doFilter(request, response);
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (!StringUtil.isEmpty(filterConfig.getInitParameter("exceptUrl"))) {
            exceptUrl = filterConfig.getInitParameter("exceptUrl");
        }
    }
}